<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>spring-aop极简入门 | haijd</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="Spring" />
  
  
  
  
  <meta name="description" content="SpringAop入门教程">
<meta name="keywords" content="Spring">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring-AOP极简入门">
<meta property="og:url" content="http://www.hais2.com/2018/05/30/Spring-AOP-Minimalist-Getting-Started/index.html">
<meta property="og:site_name" content="haijd">
<meta property="og:description" content="SpringAop入门教程">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1527701268185&di=7ca52773e094b8ee3c40a78ccdf701d9&imgtype=jpg&src=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D4172169013%2C464131932%26fm%3D214%26gp%3D0.jpg">
<meta property="og:updated_time" content="2018-06-07T14:54:45.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring-AOP极简入门">
<meta name="twitter:description" content="SpringAop入门教程">
<meta name="twitter:image" content="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1527701268185&di=7ca52773e094b8ee3c40a78ccdf701d9&imgtype=jpg&src=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D4172169013%2C464131932%26fm%3D214%26gp%3D0.jpg">
  
    <link rel="alternate" href="/atom.xml" title="haijd" type="application/atom+xml">
  
  <link rel="icon" href="/css/images/favicon.ico">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");font-weight:400;font-style:italic;}</style>
    
  <link rel="stylesheet" id="athemes-headings-fonts-css" href="//fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A200%2C300%2C400%2C700&amp;ver=4.6.1" type="text/css" media="all">
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css" >
  <link rel="stylesheet" href="/css/hiero.css" >
  <link rel="stylesheet" href="/css/glyphs.css" >
  
    <link rel="stylesheet" href="/css/vdonate.css" >
  

</head>

<script>
var themeMenus = {};

  themeMenus["/"] = "Home"; 

  themeMenus["/archives"] = "Archives"; 

  themeMenus["/categories"] = "Categories"; 

  themeMenus["/tags"] = "Tags"; 

  themeMenus["/about"] = "About"; 

</script>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  <header id="allheader" class="site-header" role="banner">
  <div class="clearfix container">
      <div class="site-branding">

          <h1 class="site-title">
            
              <a href="/" title="haijd" rel="home"> haijd </a>
            
          </h1>

          
            <div class="site-description">Stay Hungry,Stay Foolish</div>
          
            
          <nav id="main-navigation" class="main-navigation" role="navigation">
            <a class="nav-open">Menu</a>
            <a class="nav-close">Close</a>
            <div class="clearfix sf-menu">

              <ul id="main-nav" class="nmenu sf-js-enabled">
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/">Home</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/archives">Archives</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/categories">Categories</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/tags">Tags</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/about">About</a> </li>
                    
              </ul>
            </div>
          </nav>


      </div>
  </div>
</header>




  <div id="container">
    <div id="wrap">
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-Spring-AOP-Minimalist-Getting-Started" style="width: 66%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="clearfix post-1016 post type-post status-publish format-standard has-post-thumbnail hentry category-template-2 category-uncategorized tag-codex tag-edge-case tag-featured-image tag-image tag-template">
    
<div class="article-gallery">
  <div class="article-gallery-photos">
    
      <a class="article-gallery-img fancybox" href="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1527701268185&di=7ca52773e094b8ee3c40a78ccdf701d9&imgtype=jpg&src=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D4172169013%2C464131932%26fm%3D214%26gp%3D0.jpg" rel="gallery_cjie4nak4006k3swavvetudyh">
        <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1527701268185&di=7ca52773e094b8ee3c40a78ccdf701d9&imgtype=jpg&src=http%3A%2F%2Fimg3.imgtn.bdimg.com%2Fit%2Fu%3D4172169013%2C464131932%26fm%3D214%26gp%3D0.jpg" itemprop="image">
      </a>
    
  </div>
</div>

    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      Spring-AOP极简入门
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	Posted on <a href="/2018/05/30/Spring-AOP-Minimalist-Getting-Started/" class="article-date">
	  <time datetime="2018-05-30T14:36:50.000Z" itemprop="datePublished">May 30, 2018</time>
	</a>

      
	<span id="busuanzi_container_page_pv">
	  本文总阅读量<span id="busuanzi_value_page_pv"></span>次
	</span>

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <!-- TOC -->
<ul>
<li><a href="#1-apo">1. APO介绍</a><ul>
<li><a href="#11">1.1. 简介</a></li>
<li><a href="#12-aop">1.2. AOP名词</a></li>
</ul>
</li>
<li><a href="#2-java">2. Java动态代理介绍</a><ul>
<li><a href="#21">2.1. 代理模式</a></li>
<li><a href="#22-java">2.2. Java中的动态代理</a></li>
<li><a href="#23">2.3. 代码示例:</a></li>
</ul>
</li>
<li><a href="#3-cglib">3. CGLib代理</a><ul>
<li><a href="#31-cglib">3.1. cglib介绍</a></li>
<li><a href="#32-cglibjdk">3.2. cglib与JDK动态代理</a></li>
<li><a href="#33-cglib">3.3. cglib库实现代理示例：</a></li>
</ul>
</li>
<li><a href="#4-spring-aop">4. Spring AOP的实现</a><ul>
<li><a href="#41-ideamaven">4.1. 使用IDEA创建一个Maven项目，添加下列依赖：</a></li>
<li><a href="#42-hello">4.2. 创建代理类<code>Hello</code>：</a></li>
<li><a href="#43-myadvice">4.3. 创建一个增强代码类<code>MyAdvice</code>：</a></li>
<li><a href="#44-springspringxml">4.4. 接下来创建一个spring的配置文件<code>spring.xml</code></a></li>
<li><a href="#45-testaop">4.5. 测试类<code>TestAop</code>:</a></li>
<li><a href="#46">4.6. 输出：</a></li>
</ul>
</li>
<li><a href="#5-spring-aop">5. 使用注解实现Spring AOP</a></li>
<li><a href="#6">6. 参考资料</a></li>
</ul>
<!-- /TOC -->
<h1 id="1-APO介绍"><a href="#1-APO介绍" class="headerlink" title="1. APO介绍"></a>1. APO介绍</h1><h2 id="1-1-简介"><a href="#1-1-简介" class="headerlink" title="1.1. 简介"></a>1.1. 简介</h2><p>按照惯例先来一份<a href="https://zh.wikipedia.org/wiki/面向侧面的程序设计" target="_blank" rel="noopener">维基百科的解释</a>：</p>
<blockquote>
<p>面向侧面的程序设计（aspect-oriented programming，AOP，又译作面向方面的程序设计、观点导向编程、剖面导向程序设计）是计算机科学中的一个术语，指一种程序设计范型。该范型以一种称为侧面（aspect，又译作方面）的语言构造为基础，侧面是一种新的模块化机制，用来描述分散在对象、类或函数中的横切关注点（crosscutting concern）。<a id="more"></a></p>
</blockquote>
<p>一句话解释AOP就是：AOP可以在不修改源码的情况下对程序进行增强。</p>
<p>举个栗子：<img src="/image/face/举个栗子.jpg" alt="举个栗子"><br>　　用这个简图示范一下AOP的具体使用，可能会更容易理解AOP是什么。<br>　　假设我们已经完成了所有的Web、Service、Dao层的代码，但是现在程序出了Bug，这时你想到在程序中加入日志，每当程序出现异常，就记录下来异常的信息，方便排查，这样做很对，但是代码已经很多了，不可能在每个Method中都加入一个记录日志的代码，这样做太麻烦了，而且很不优雅。<br>　　这时候，我们的AOP就上场了，不用改动任何的现有代码，只需加入记录日志操作的代码，并且配置每当程序抛出未捕获(或者任何异常)异常时就记录日志。<br>　　又或者是，在Service调用Dao层的数据库操作代码前后，加入事务。<br>　　这里的<em>日志记录问题</em>和<em>事务记录问题</em>就是<strong>横切关注点</strong>。<br>　　不破坏现有的业务代码对程序增加功能，这就是AOP存在的意义。<br><img src="/image/Java/111111.png" alt="AOP演示"></p>
<h2 id="1-2-AOP名词"><a href="#1-2-AOP名词" class="headerlink" title="1.2. AOP名词"></a>1.2. AOP名词</h2><ul>
<li><code>Joinpoint</code>(连接点)：目标对象中所有可以被增强的方法。</li>
<li><code>Pointcut</code>(切入点)：目标对象中已经被增强的方法。</li>
<li><code>Advice</code>(通知)：用来增强的代码。</li>
<li><code>Target</code>(目标对象)：被代理的对象。</li>
<li><code>Weaving</code>(织入)：将通知(Advice)应用到切入点(Pointcut)的过程。</li>
<li><code>Proxy</code>(代理)：将通知织入到目标对象之后形成代理对象。</li>
<li><code>Aspect</code>(切面)：切入点(Pointcut)<strong>+</strong>(Advice)通知。</li>
</ul>
<h1 id="2-Java动态代理介绍"><a href="#2-Java动态代理介绍" class="headerlink" title="2. Java动态代理介绍"></a>2. Java动态代理介绍</h1><h2 id="2-1-代理模式"><a href="#2-1-代理模式" class="headerlink" title="2.1. 代理模式"></a>2.1. 代理模式</h2><p>　　介绍Java的动态代理之前，先提一下代理模式，代理模式就是为其他对象提供一种代理，以控制对这个对象的访问。这么说可能不好理解，举个例子：我们现在要租房子，一般都是通过中介公司找房子，而不是直接找房东，在这个过程中中介公司就相当于一个代理(Proxy)，我们(client)并不能直接和房东(bean)联系，而是通过中介的联系，这样的好处就是，房东不用到处找客户，只需要把房子交给中介，自己该干嘛干嘛，而我们只需要找到靠谱的中介，就免去了和房东的一些理不清的纠纷。<br>　　而程序中的代理，就是为了给我们已经写好的代码增强功能，也就是AOP的具体实现模式。</p>
<h2 id="2-2-Java中的动态代理"><a href="#2-2-Java中的动态代理" class="headerlink" title="2.2. Java中的动态代理"></a>2.2. Java中的动态代理</h2><p>　　动态类型语言入python、ruby等，可以在运行时动态的对类进行修改，而在Java中这是不被允许的，因为Java属于静态类型语言，运行时类已经被编译成字节码，无法对其进行修改(并不绝对，我们接下来介绍的CGLib就是个例外)。<br>　　为了实现在运行时动态的修改类型定义，Java5引入了一个新特性就是动态代理，而这个特性并不是特别的优雅，Java规定了需要动态代理的类，必须实现接口才行，这样被代理类和动态创建的代理类都会继承该接口，从而实现类的代理。</p>
<h2 id="2-3-代码示例"><a href="#2-3-代码示例" class="headerlink" title="2.3. 代码示例:"></a>2.3. 代码示例:</h2><p>接口<code>IHello</code>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> Proxy_1;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">IHello</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sayHello</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>被代理对象<code>Hello</code>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> Proxy_1;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Hello</span> <span class="keyword">implements</span> <span class="title">IHello</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sayHello</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"Hello World!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>代理实现类<code>ProxyHandler</code>：<br>Java规定，代理实现类必须继承<code>InvocationHandler</code>接口，并且实现其<code>invoke</code>方法。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> Proxy_1;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.InvocationHandler;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Proxy;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ProxyHandler</span> <span class="keyword">implements</span> <span class="title">InvocationHandler</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Object target;</span><br><span class="line">    <span class="comment">// 绑定被代理对象，返回代理</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">bind</span><span class="params">(Object target)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.target=target;</span><br><span class="line">        <span class="comment">// 返回生成的代理</span></span><br><span class="line">        <span class="keyword">return</span> Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),<span class="keyword">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 这里就是写扩展代码的地方</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">invoke</span><span class="params">(Object proxy, Method method, Object[] args)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        Object result;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">/*目标方法调用之前*/</span></span><br><span class="line">        System.out.print(<span class="string">"Before sayHello\n"</span>);</span><br><span class="line">        result=method.invoke(target,args);</span><br><span class="line">        <span class="comment">/*目标方法调用之后*/</span></span><br><span class="line">        System.out.print(<span class="string">"\nAfter sayHello"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>测试类<code>TestProxy</code>：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Proxy_1.Hello;</span><br><span class="line"><span class="keyword">import</span> Proxy_1.IHello;</span><br><span class="line"><span class="keyword">import</span> Proxy_1.ProxyHandler;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestProxy</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span></span>&#123;</span><br><span class="line">        ProxyHandler proxy=<span class="keyword">new</span> ProxyHandler();</span><br><span class="line"></span><br><span class="line">        IHello hello=(IHello)proxy.bind(<span class="keyword">new</span> Hello());</span><br><span class="line">        hello.sayHello();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>输出：<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Before sayHello</span><br><span class="line">Hello World!</span><br><span class="line">After sayHello</span><br></pre></td></tr></table></figure></p>
<h1 id="3-CGLib代理"><a href="#3-CGLib代理" class="headerlink" title="3. CGLib代理"></a>3. CGLib代理</h1><h2 id="3-1-cglib介绍"><a href="#3-1-cglib介绍" class="headerlink" title="3.1. cglib介绍"></a>3.1. cglib介绍</h2><p>　　<a href="https://github.com/cglib/cglib" target="_blank" rel="noopener">cglib</a>是一个开源的Java类库，提供了比Java动态代理更加强大的代理功能，cglib不需要动态代理的对象实现任何接口，比起Java自身的动态代理着实好用了许多。</p>
<h2 id="3-2-cglib与JDK动态代理"><a href="#3-2-cglib与JDK动态代理" class="headerlink" title="3.2. cglib与JDK动态代理"></a>3.2. cglib与JDK动态代理</h2><p>cglib和Java动态代理的主要区别：</p>
<ul>
<li>Java动态代理是利用反射机制生成一个实现代理接口的匿名类，在调用目标方法前调用<code>InvokeHandler</code>来执行一些自定义的处理。</li>
<li>cglib底层使用了一个<code>ASM</code>开源包，直接对代理对象编译后的class文件进行修改，修改其字节码，给代理对象生成一个子类，由子类实现代理功能。</li>
<li>实现方式上，Java动态代理使用的是反射查找指定接口的实现类；cglib是给代理对象生成子类，从而继承其能力，实现代理功能。</li>
<li>如果目标对象被<code>final</code>修饰，那么该类就无法被cglib代理了。</li>
</ul>
<p>两种方式对比，cglib比较方便灵活一些，在spring-aop中两种代理方式都使用到了，默认情况下使用的是Java动态代理，但是如果目标对象没有实现接口，那么必须强制使用cglib库进行代理。<br>强制使用cglib需要在spring配置中加入：<code>&lt;aop:aspectj-autoproxy proxy-target-class=&quot;true&quot;/&gt;</code></p>
<h2 id="3-3-cglib库实现代理示例："><a href="#3-3-cglib库实现代理示例：" class="headerlink" title="3.3. cglib库实现代理示例："></a>3.3. cglib库实现代理示例：</h2><p>代理对象<code>Hello</code>：<br>使用cglib不需要实现任何接口。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> dome_1;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Hello</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sayHello</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.print(<span class="string">"Hello World!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Cglib代理类<code>CglibProxyHandler</code>:<br>需要继承cglib库的<code>MethodInterceptor</code>的<code>intercept</code>方法，该方法类似于JDK代理的<code>invoke</code>方法。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> dome_1;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> net.sf.cglib.proxy.Enhancer;</span><br><span class="line"><span class="keyword">import</span> net.sf.cglib.proxy.MethodInterceptor;</span><br><span class="line"><span class="keyword">import</span> net.sf.cglib.proxy.MethodProxy;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CglibProxyHandler</span> <span class="keyword">implements</span> <span class="title">MethodInterceptor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 获得一个代理对象实例</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">getProxy</span><span class="params">(Class c)</span></span>&#123;</span><br><span class="line">        Enhancer enhancer=<span class="keyword">new</span> Enhancer();</span><br><span class="line">        enhancer.setSuperclass(c);</span><br><span class="line">        enhancer.setCallback(<span class="keyword">this</span>);</span><br><span class="line">        <span class="keyword">return</span> enhancer.create();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object o, Method method, Object[] objects, MethodProxy methodProxy)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        <span class="comment">/*目标方法调用之前*/</span></span><br><span class="line">        System.out.print(<span class="string">"Before sayHello\n"</span>);</span><br><span class="line">        Object returnValue = methodProxy.invokeSuper(o, objects);</span><br><span class="line">        <span class="comment">/*目标方法调用之后*/</span></span><br><span class="line">        System.out.print(<span class="string">"\nAfter sayHello"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> returnValue;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>测试类<code>TestProxy</code>:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> dome_1.CglibProxyHandler;</span><br><span class="line"><span class="keyword">import</span> dome_1.Hello;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestProxy</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span></span>&#123;</span><br><span class="line">        CglibProxyHandler proxy=<span class="keyword">new</span> CglibProxyHandler();</span><br><span class="line">        <span class="comment">// 获得一个代理对象</span></span><br><span class="line">        Hello hello=(Hello) proxy.getProxy(Hello.class);</span><br><span class="line">        hello.sayHello();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>执行结果：<br><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Before sayHello</span><br><span class="line">Hello World!</span><br><span class="line">After sayHello</span><br></pre></td></tr></table></figure></p>
<h1 id="4-Spring-AOP的实现"><a href="#4-Spring-AOP的实现" class="headerlink" title="4. Spring AOP的实现"></a>4. Spring AOP的实现</h1><h2 id="4-1-使用IDEA创建一个Maven项目，添加下列依赖："><a href="#4-1-使用IDEA创建一个Maven项目，添加下列依赖：" class="headerlink" title="4.1. 使用IDEA创建一个Maven项目，添加下列依赖："></a>4.1. 使用IDEA创建一个Maven项目，添加下列依赖：</h2><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependencies&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;cglib&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;cglib&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;3.2.6&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-context&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;4.3.17.RELEASE&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-aspects&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;4.3.17.RELEASE&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-aop&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;4.3.17.RELEASE&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.aspectj&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;aspectjrt&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;1.9.1&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.aspectj&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;aspectjtools&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;1.9.1&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">    &lt;/dependencies&gt;</span><br></pre></td></tr></table></figure>
<h2 id="4-2-创建代理类Hello："><a href="#4-2-创建代理类Hello：" class="headerlink" title="4.2. 创建代理类Hello："></a>4.2. 创建代理类<code>Hello</code>：</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> spring_aop;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Hello</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listen</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Listen Hello World!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">speak</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Speak Hello World!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">read</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Read Hello World!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">write</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"Write Hello World!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4-3-创建一个增强代码类MyAdvice："><a href="#4-3-创建一个增强代码类MyAdvice：" class="headerlink" title="4.3. 创建一个增强代码类MyAdvice："></a>4.3. 创建一个增强代码类<code>MyAdvice</code>：</h2><p>AOP的五种通知类型：<br><strong>前置通知</strong>(<code>before</code>) ：在目标方法执行之前执行。<br><strong>后置通知</strong>(<code>after-returning</code>) ：在目标方法执行之后执行,出现异常时不会执行。<br><strong>环绕通知</strong>(<code>around</code>) ：在目标方法执行前和执行后执行。<br><strong>异常抛出通知</strong>(<code>after-throwing</code>)：在目标方法执行出现异常的时候执行。<br><strong>最终通知</strong>(<code>after</code>) ：无论目标方法是否出现异常最终通知都会执行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> spring_aop;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.aspectj.lang.ProceedingJoinPoint;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyAdvice</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"我是前置通知"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterReturning</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"我是后置通知(出现异常不会调用我)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">around</span><span class="params">(ProceedingJoinPoint pjp)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"我是环绕在切入点之前的通知"</span>);</span><br><span class="line">        Object proceed = pjp.proceed();   <span class="comment">// 调用目标方法</span></span><br><span class="line">        System.out.println(<span class="string">"我是环绕在切入点之后的通知"</span>);</span><br><span class="line">        <span class="keyword">return</span> proceed;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 程序抛出异常的时候，会调用该方法，可以在此收集日志。</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterException</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"出现异常啦！！！"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">after</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"我是后置通知(出现异常也会调用我)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4-4-接下来创建一个spring的配置文件spring-xml"><a href="#4-4-接下来创建一个spring的配置文件spring-xml" class="headerlink" title="4.4. 接下来创建一个spring的配置文件spring.xml"></a>4.4. 接下来创建一个spring的配置文件<code>spring.xml</code></h2><p>切点表达式简介(针对下面的表达式解释，具体请查阅网络更详细的解释)：</p>
<table>
<thead>
<tr>
<th style="text-align:left">符号</th>
<th style="text-align:left">含义</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left"><code>execution()</code></td>
<td style="text-align:left">表示切点表达式的主体</td>
</tr>
<tr>
<td style="text-align:left">第一个<code>*</code></td>
<td style="text-align:left">表示返回值，<code>*</code>表示任意返回值</td>
</tr>
<tr>
<td style="text-align:left">spring_aop.Hello</td>
<td style="text-align:left">切点所在的类名，需要完全限定名</td>
</tr>
<tr>
<td style="text-align:left">包名后的<code>.</code></td>
<td style="text-align:left">表示当前类(包)，<code>..</code>两个点就表示当前的包和子包</td>
</tr>
<tr>
<td style="text-align:left">第二个<code>*</code></td>
<td style="text-align:left">表示该类下所有的方法</td>
</tr>
<tr>
<td style="text-align:left"><code>(..)</code></td>
<td style="text-align:left">表示方法可以有任意参数</td>
</tr>
</tbody>
</table>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=<span class="string">"1.0"</span> encoding=<span class="string">"UTF-8"</span>?&gt;</span><br><span class="line">&lt;beans xmlns=<span class="string">"http://www.springframework.org/schema/beans"</span></span><br><span class="line">       xmlns:xsi=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span> xmlns:aop=<span class="string">"http://www.springframework.org/schema/aop"</span></span><br><span class="line">       xsi:schemaLocation=<span class="string">"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"</span>&gt;</span><br><span class="line"></span><br><span class="line">    &lt;bean name="hello" class="spring_aop.Hello"&gt;&lt;/bean&gt;</span><br><span class="line">    &lt;bean name="myAdvice" class="spring_aop.MyAdvice"&gt;&lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">    &lt;aop:config&gt;</span><br><span class="line">        &lt;aop:pointcut id=<span class="string">"muSay"</span> expression=<span class="string">"execution(* spring_aop.Hello.*(..))"</span>/&gt;</span><br><span class="line">        &lt;aop:aspect ref=<span class="string">"myAdvice"</span>&gt;</span><br><span class="line">            &lt;aop:before method=<span class="string">"before"</span> pointcut-ref=<span class="string">"muSay"</span>/&gt;</span><br><span class="line">            &lt;aop:after-returning method=<span class="string">"afterReturning"</span> pointcut-ref=<span class="string">"muSay"</span>/&gt;</span><br><span class="line">            &lt;aop:around method=<span class="string">"around"</span> pointcut-ref=<span class="string">"muSay"</span>/&gt;</span><br><span class="line">            &lt;aop:after-throwing method=<span class="string">"afterException"</span> pointcut-ref=<span class="string">"muSay"</span>/&gt;</span><br><span class="line">            &lt;aop:after method=<span class="string">"after"</span> pointcut-ref=<span class="string">"muSay"</span>/&gt;</span><br><span class="line">        &lt;/aop:aspect&gt;</span><br><span class="line">    &lt;/aop:config&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure>
<h2 id="4-5-测试类TestAop"><a href="#4-5-测试类TestAop" class="headerlink" title="4.5. 测试类TestAop:"></a>4.5. 测试类<code>TestAop</code>:</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.support.ClassPathXmlApplicationContext;</span><br><span class="line"><span class="keyword">import</span> spring_aop.Hello;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestAop</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String args[])</span></span>&#123;</span><br><span class="line">        <span class="comment">//1 创建容器对象</span></span><br><span class="line">        ClassPathXmlApplicationContext ac;</span><br><span class="line">        ac = <span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">"spring.xml"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 从容器中获取bean</span></span><br><span class="line">        Hello hello=(Hello)ac.getBean(<span class="string">"hello"</span>);</span><br><span class="line">        hello.listen();</span><br><span class="line">        System.out.println(<span class="string">"*****************"</span>);</span><br><span class="line">        hello.speak();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4-6-输出："><a href="#4-6-输出：" class="headerlink" title="4.6. 输出："></a>4.6. 输出：</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">我是前置通知</span><br><span class="line">我是环绕在切入点之前的通知</span><br><span class="line">Listen Hello World!</span><br><span class="line">我是后置通知(出现异常也会调用我)</span><br><span class="line">我是环绕在切入点之后的通知</span><br><span class="line">我是后置通知(出现异常不会调用我)</span><br><span class="line">*****************</span><br><span class="line">我是前置通知</span><br><span class="line">我是环绕在切入点之前的通知</span><br><span class="line">Speak Hello World!</span><br><span class="line">我是后置通知(出现异常也会调用我)</span><br><span class="line">我是环绕在切入点之后的通知</span><br><span class="line">我是后置通知(出现异常不会调用我)</span><br></pre></td></tr></table></figure>
<h1 id="5-使用注解实现Spring-AOP"><a href="#5-使用注解实现Spring-AOP" class="headerlink" title="5. 使用注解实现Spring AOP"></a>5. 使用注解实现Spring AOP</h1><p>使用注解则省去了spring中的<code>aop:config</code>配置，只需要增加一个使用注解的配置<code>&lt;aop:aspectj-autoproxy&gt;&lt;/aop:aspectj-autoproxy&gt;</code>即可：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="php"><span class="meta">&lt;?</span>xml version=<span class="string">"1.0"</span> encoding=<span class="string">"UTF-8"</span><span class="meta">?&gt;</span></span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">"http://www.springframework.org/schema/beans"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">"http://www.w3.org/2001/XMLSchema-instance"</span> <span class="attr">xmlns:aop</span>=<span class="string">"http://www.springframework.org/schema/aop"</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置通知对象 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">"hello"</span> <span class="attr">class</span>=<span class="string">"spring_aop.Hello"</span>&gt;</span><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置通知对象 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">"myAdvice"</span> <span class="attr">class</span>=<span class="string">"spring_aop.MyAdvice"</span>&gt;</span><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 开启使用注解 --&gt;</span></span><br><span class="line">	<span class="tag">&lt;<span class="name">aop:aspectj-autoproxy</span>&gt;</span><span class="tag">&lt;/<span class="name">aop:aspectj-autoproxy</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>在<code>MyAdvice</code>类中使用注解标记各个通知即可：</p>
<ul>
<li><code>@Aspect</code>表示这个类是一个通知类。</li>
<li><code>@Pointcut</code>可以标记一个空方法，当通知类里面的切点表达式相同时，可以定义一个公用的切点表达式方法，在其他注解就可以直接使用该方法的完全限定名了。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> spring_aop;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.aspectj.lang.ProceedingJoinPoint;</span><br><span class="line"><span class="keyword">import</span> org.aspectj.lang.annotation.*;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Aspect</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyAdvice</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 定义一个公用的切点表达式</span></span><br><span class="line">    <span class="meta">@Pointcut</span>(<span class="string">"execution(* spring_aop.Hello.*(..))"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">expression</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Before</span>(<span class="string">"spring_aop.MyAdvice.expression()"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">before</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"我是前置通知"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@AfterReturning</span>(<span class="string">"spring_aop.MyAdvice.expression()"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterReturning</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"我是后置通知(出现异常不会调用我)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@Around</span>(<span class="string">"execution(* spring_aop.Hello.*(..))"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">around</span><span class="params">(ProceedingJoinPoint pjp)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"我是环绕在切入点之前的通知"</span>);</span><br><span class="line">        Object proceed = pjp.proceed();   <span class="comment">// 调用目标方法</span></span><br><span class="line">        System.out.println(<span class="string">"我是环绕在切入点之后的通知"</span>);</span><br><span class="line">        <span class="keyword">return</span> proceed;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@AfterThrowing</span>(<span class="string">"execution(* spring_aop.Hello.*(..))"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterException</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"出现异常啦！！！"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@After</span>(<span class="string">"execution(* spring_aop.Hello.*(..))"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">after</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"我是后置通知(出现异常也会调用我)"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="6-参考资料"><a href="#6-参考资料" class="headerlink" title="6. 参考资料"></a>6. 参考资料</h1><p><a href="https://zh.wikipedia.org/wiki/面向侧面的程序设计" target="_blank" rel="noopener">https://zh.wikipedia.org/wiki/面向侧面的程序设计</a><br><a href="https://baike.baidu.com/item/Aspectj" target="_blank" rel="noopener">https://baike.baidu.com/item/Aspectj</a><br><a href="https://blog.csdn.net/ABCD898989/article/details/50809321" target="_blank" rel="noopener">https://blog.csdn.net/ABCD898989/article/details/50809321</a><br>《Spring实战第四版》</p>

      
    </div>
    <footer class="entry-meta entry-footer">
      
	<span class="ico-folder"></span>
    <a class="article-category-link" href="/categories/Java/">Java</a>

      
  <span class="ico-tags"></span>
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Spring/">Spring</a></li></ul>

      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!', // 可选参数，打赏标题
  btnText: 'Donate', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: '/css/images/wechatPay.png',
  alipayImage: '/css/images/alipay.jpg'
});
</script>
      

      
        
	<section id="comments" class="comment">
	  <div id="disqus_thread">
	  <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
	  </div>
	</section>

	<script type="text/javascript">
	var disqus_shortname = 'haijdblog';
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/count.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	</script>


      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2018/06/12/Spring-Core-Annotations-1/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          Spring Core Annotations
        
      </div>
    </a>
  
  
    <a href="/2018/04/15/5-minutes-to-fit-the-TypeScript/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">5分钟概览TypeScript</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">Contents</strong>
    
      <ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-APO介绍"><span class="nav-number">1.</span> <span class="nav-text">1. APO介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-简介"><span class="nav-number">1.1.</span> <span class="nav-text">1.1. 简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-AOP名词"><span class="nav-number">1.2.</span> <span class="nav-text">1.2. AOP名词</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-Java动态代理介绍"><span class="nav-number">2.</span> <span class="nav-text">2. Java动态代理介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-代理模式"><span class="nav-number">2.1.</span> <span class="nav-text">2.1. 代理模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-Java中的动态代理"><span class="nav-number">2.2.</span> <span class="nav-text">2.2. Java中的动态代理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-代码示例"><span class="nav-number">2.3.</span> <span class="nav-text">2.3. 代码示例:</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-CGLib代理"><span class="nav-number">3.</span> <span class="nav-text">3. CGLib代理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-cglib介绍"><span class="nav-number">3.1.</span> <span class="nav-text">3.1. cglib介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-cglib与JDK动态代理"><span class="nav-number">3.2.</span> <span class="nav-text">3.2. cglib与JDK动态代理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-cglib库实现代理示例："><span class="nav-number">3.3.</span> <span class="nav-text">3.3. cglib库实现代理示例：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-Spring-AOP的实现"><span class="nav-number">4.</span> <span class="nav-text">4. Spring AOP的实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-使用IDEA创建一个Maven项目，添加下列依赖："><span class="nav-number">4.1.</span> <span class="nav-text">4.1. 使用IDEA创建一个Maven项目，添加下列依赖：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-创建代理类Hello："><span class="nav-number">4.2.</span> <span class="nav-text">4.2. 创建代理类Hello：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-创建一个增强代码类MyAdvice："><span class="nav-number">4.3.</span> <span class="nav-text">4.3. 创建一个增强代码类MyAdvice：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-4-接下来创建一个spring的配置文件spring-xml"><span class="nav-number">4.4.</span> <span class="nav-text">4.4. 接下来创建一个spring的配置文件spring.xml</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-5-测试类TestAop"><span class="nav-number">4.5.</span> <span class="nav-text">4.5. 测试类TestAop:</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-6-输出："><span class="nav-number">4.6.</span> <span class="nav-text">4.6. 输出：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-使用注解实现Spring-AOP"><span class="nav-number">5.</span> <span class="nav-text">5. 使用注解实现Spring AOP</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#6-参考资料"><span class="nav-number">6.</span> <span class="nav-text">6. 参考资料</span></a></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      <footer id="footer" class="site-footer">
  

  <div class="clearfix container">
      <div class="site-info">
	      &copy; 2018 haijd All Rights Reserved.
          
            <span id="busuanzi_container_site_uv">
              本站访客数<span id="busuanzi_value_site_uv"></span>人次  
              本站总访问量<span id="busuanzi_value_site_pv"></span>次
            </span>
          
      </div>
      <div class="site-credit">
        Theme by <a href="https://github.com/iTimeTraveler/hexo-theme-hiero" target="_blank">hiero</a>
      </div>
  </div>
</footer>


<!-- min height -->

<script>
    var contentdiv = document.getElementById("content");

    contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("allheader").offsetHeight - document.getElementById("footer").offsetHeight + "px";
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/main.js"></script>








	<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js" async=""></script>
</body>
</html>
